/******************************************************************
 * @version      : 1.0
 * @Author       : zhl
 * @Date         : 2023-06-27 17:23:20
 * @LastEditors  : zhl
 * @E-Mail       : zhll168@163.com
 * @Description  : 业务描述
 ******************************************************************/
#include <memory>
#include <string>
#include <iostream>
#include "LinkManager.h"
#include "Link-APDU.h"
#include "DLT698Manager.h"

#define LINK_DATA_LEN 128


LinkManager LinkManager::c_link_manager;

LinkManager::LinkManager(/* args */){
    c_link_data_len = LINK_DATA_LEN;
    c_link_data = (uint8_t *)malloc(c_link_data_len);
}

LinkManager::~LinkManager(){
    if(NULL != c_link_data){
        free(c_link_data);
    }
}

LinkManager& LinkManager::getInstance(){
    return c_link_manager;
}

int LinkManager::get_link_frame(APDU& apdu){
    DLT698_FRAME frame;
    DLT698Manager::get_instance().init();
    c_link_data_len = DLT698Manager::get_instance().packet_frame(frame, c_link_data, c_link_data_len, apdu);
    return c_link_data_len;
}

uint8_t *LinkManager::get_link_request_frame(LINK_REQUEST_TYPE type, uint16_t heartbeat_interval){
    APDU  apdu = Link_APDU::getInstance().packet(LINK_REQUEST, type, heartbeat_interval);
     if( 0 > get_link_frame(apdu)){
        return NULL;
    }
    return c_link_data;
}

uint8_t *LinkManager::get_link_response_frame(LINK_REQUEST_TYPE type, uint16_t heartbeat_interval){
    APDU  apdu = Link_APDU::getInstance().packet(LINK_RESPONSE, type, heartbeat_interval);
    if( 0 > get_link_frame(apdu)){
        return NULL;
    }
    return c_link_data;
}

int LinkManager::get_link_apdu_length(){
    return c_link_data_len;
}

int LinkManager::link(std::weak_ptr<CConfigManager> cm){
    auto run_param = cm.lock()->get_dlt698_run_param();
    if(nullptr == run_param){
        return -1;
    }
    if(run_param->mode == RUN_MODE_MASTER){
        if(NULL == get_link_request_frame(LINK_REQ_LOGIN, run_param->heartbeat_interval)){
            return -1;
        }
        //发送登录报文。
        //
        if(NULL == get_link_request_frame(LINK_REQ_HEARTBEAT, run_param->heartbeat_interval)){
            return -1;
        }
        //发送心跳报文。
    } else if(run_param->mode == RUN_MODE_SLAVE){

    }
}